/**
 * 
 */
package com.ar.myshares.daos;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;

import com.ar.myshares.model.Instrument;
import com.ar.myshares.model.Operation;

/**
 * @author mac
 *
 */
public class OperationDAOImpl implements OperationDAO {

	private HibernateTemplate template;

	@Autowired
	private InstrumentDAO instrumentDAO;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		template = new HibernateTemplate(sessionFactory);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ar.myshares.daos.OperationDAO#getOperation(long)
	 */
	@Override
	public Operation getOperation(long id) {
		return template.get(Operation.class, Long.valueOf(id));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ar.myshares.daos.OperationDAO#getAllOperations()
	 */
	@Override
	public List<Operation> getAllOperations() {
		return template.loadAll(Operation.class);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ar.myshares.daos.OperationDAO#saveOperation(com.ar.myshares.model
	 * .Operation)
	 */
	@Override
	public Operation saveOperation(Operation operation) {
		// Check if the instrument already exists in the DB
		if (operation.getInstrument().getId() == -1) {
			Instrument instrument = this.instrumentDAO.getInstrument(operation.getInstrument().getSymbol());
			if (instrument != null) {
				operation.setInstrument(instrument);
			}
		}
		operation.setId(((Long) template.save(operation)).longValue());
		return operation;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.ar.myshares.daos.OperationDAO#removeOperation(com.ar.myshares.model
	 * .Operation)
	 */
	@Override
	public void removeOperation(Operation operation) {
		template.delete(operation);
	}

}
